﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DigitalRune.Windows.Docking;
using CalemShop.Classes;
using Microsoft.Win32;
using System.Threading;

namespace CalemShop.Forms
{
    public delegate void UpdateProgressingCallBack(int percentage, string message);
    public delegate void UpdateStatusMessageCallBack(string message);

    public partial class FrmCalemShop : Form
    {
        private static RegistryKey registryKey = null;
        private FrmInvoiceExplorer frmInvoiceExp = null;
        private FrmInvoiceDetail frmInvoiceDetail = null;
        private FrmImportItemFromBarcode frmImportItemBranch = null;
        private FrmBarcodePrinter frmBarcodePrinter = null;
        private FrmCheckStock frmCheckStock = null;
        private FrmReportIncome frmReportIncome = null;
        private FrmInputStock frmInputStock = null;
        private FrmSearchItem frmSearchItem = null;
        private FrmCustomerExplorer frmCustomer = null;
        private FrmStaff frmStaff = null;
        private bool isReportStop = false;
        private Thread reportThread;
        private static bool hasSendReport = false;
        private static bool hasBackup = false;
        
        public FrmCalemShop()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            dockPanel.ActiveDocumentChanged += new EventHandler(dockPanel_ActiveDocumentChanged);
            reportThread = new Thread(new ThreadStart(doDailyReport));
        }

        void dockPanel_ActiveDocumentChanged(object sender, EventArgs e)
        {
            IDockableForm f = dockPanel.ActiveDocument;
            if (f != null && f is FrmBaseDock)
            {
                FrmBaseDock ff = f as FrmBaseDock;
                ff.FormActived();
            }
        }

        private void FrmCalemShop_Load(object sender, EventArgs e)
        {
            try
            {
                registryKey = Registry.CurrentUser.CreateSubKey(@"Software\Calem");
                this.Text = RuntimeData.GetShopTitle();
                DBConnection.ConnectionString = RuntimeData.GetSqlConnectionString();
                reportThread.Start();
                UpdateStatusMessage("Daily report is active");
            }
            catch (Exception ee)
            {
                Reporter.WriteErrorEx(ee);
            }

        }

        public void UpdateProgressBar(int percentage, string message)
        {
            if (this.InvokeRequired)
            {
                UpdateProgressingCallBack cb = new UpdateProgressingCallBack(this.UpdateProgressBar);
                this.Invoke(cb, percentage, message);
            }
            else
            {
                if (percentage <= 0 || percentage > 100)
                {
                    progresssBar.Value = 0;
                }
                else
                {
                    progresssBar.Value = percentage;
                }

                if (string.IsNullOrEmpty(message))
                {
                    lbStatus.Text = "Done";
                }
                else
                {
                    lbStatus.Text = message;
                }
            }
        }

        public void UpdateStatusMessage(string message)
        {
            if (this.InvokeRequired)
            {
                UpdateStatusMessageCallBack cb = new UpdateStatusMessageCallBack(this.UpdateStatusMessage);
                this.Invoke(cb, message);
            }
            else
            {
                if (string.IsNullOrEmpty(message))
                {
                    lbStatus.Text = "Done";
                }
                else
                {
                    lbStatus.Text = message;
                }
            }
        }

        private void mnSale_Click(object sender, EventArgs e)
        {
            ShowSaleForm();
        }

        private void ShowSaleForm()
        {
            IDockableForm[] forms = dockPanel.DocumentsToArray();
            int index = 0;
            foreach (IDockableForm f in forms)
            {
                if (f is FrmSale)
                {
                    FrmSale fs = (FrmSale)f ;
                    if (index < fs.FormIndex)
                    {
                        index = fs.FormIndex;
                    }
                }
            }

            FrmSale frm = new FrmSale(this);
            frm.FormIndex = ++index;
            frm.Text = "Giỏ hàng " + index;
            frm.TabText = frm.Text;
            frm.SetPrinterName(GetBillPrinterNameFromRegistry());
            frm.Display(DigitalRune.Windows.Docking.DockState.Document);
        }

        public void ShowReportIncome()
        {
            if (frmReportIncome == null || frmReportIncome.IsDisposed)
            {
                frmReportIncome = new FrmReportIncome(this);
                frmReportIncome.Text = "Báo cáo doanh thu";
                frmReportIncome.TabText = frmReportIncome.Text;
            }
            frmReportIncome.Display(DigitalRune.Windows.Docking.DockState.Document);
        }

        public void ShowBarcodePrinter()
        {
            if (frmBarcodePrinter == null || frmBarcodePrinter.IsDisposed)
            {
                frmBarcodePrinter = new FrmBarcodePrinter(this);
                frmBarcodePrinter.Text = "In Barcode";
                frmBarcodePrinter.TabText = frmBarcodePrinter.Text;
            }
            frmBarcodePrinter.Display(DigitalRune.Windows.Docking.DockState.Document);
        }

        public void ShowInvoiceExplorerForm()
        {
            if (frmInvoiceExp == null || frmInvoiceExp.IsDisposed)
            {
                frmInvoiceExp = new FrmInvoiceExplorer(this);
                frmInvoiceExp.Text = "Danh sách hóa đơn";
                frmInvoiceExp.TabText = frmInvoiceExp.Text;
            }
            frmInvoiceExp.Display(DigitalRune.Windows.Docking.DockState.DockLeft);
        }


        public void ShowImportItemBranchForm()
        {
            if (frmImportItemBranch == null || frmImportItemBranch.IsDisposed)
            {
                frmImportItemBranch = new FrmImportItemFromBarcode(this);
                frmImportItemBranch.Text = "Nhập hàng từ chi nhánh";
                frmImportItemBranch.TabText = frmImportItemBranch.Text;
                frmImportItemBranch.Display(DigitalRune.Windows.Docking.DockState.Document);
            }
        }

        public void ShowCheckStockForm()
        {
            if (frmCheckStock == null || frmCheckStock.IsDisposed)
            {
                frmCheckStock = new FrmCheckStock(this);
                frmCheckStock.Text = "Kiểm kho";
                frmCheckStock.TabText = frmCheckStock.Text;
                frmCheckStock.Display(DigitalRune.Windows.Docking.DockState.Document);
            }

            frmCheckStock.Display(DigitalRune.Windows.Docking.DockState.Document);
            
        }

        public void ShowInputStockForm()
        {
            if (frmInputStock == null || frmInputStock.IsDisposed)
            {
                frmInputStock = new FrmInputStock(this);
                frmInputStock.Text = "Nhập hàng";
                frmInputStock.TabText = frmInputStock.Text;
                frmInputStock.Display(DigitalRune.Windows.Docking.DockState.Document);
            }

            frmInputStock.Display(DigitalRune.Windows.Docking.DockState.Document);

        }

        public void ShowCustomerForm()
        {
            if (frmCustomer == null || frmCustomer.IsDisposed)
            {
                frmCustomer = new FrmCustomerExplorer(this);
                frmCustomer.Text = "Quản lý khách hàng";
                frmCustomer.TabText = frmCustomer.Text;
                frmCustomer.Display(DigitalRune.Windows.Docking.DockState.Document);
            }

            frmCustomer.Display(DigitalRune.Windows.Docking.DockState.Document);

        }

        public void ShowStaffForm()
        {
            if (frmStaff == null || frmStaff.IsDisposed)
            {
                frmStaff = new FrmStaff(this);
                frmStaff.Text = "Quản nhân viên";
                frmStaff.TabText = frmStaff.Text;
                frmStaff.Display(DigitalRune.Windows.Docking.DockState.Document);
            }

            frmStaff.Display(DigitalRune.Windows.Docking.DockState.Document);

        }

        public void ShowSearchItemForm()
        {
            if (frmSearchItem == null || frmSearchItem.IsDisposed)
            {
                frmSearchItem = new FrmSearchItem(this);
                frmSearchItem.ShowInTaskbar = false;
                frmSearchItem.StartPosition = FormStartPosition.CenterScreen;
                frmSearchItem.Text = "Tìm kiếm sản phẩm";
                frmSearchItem.TabText = frmSearchItem.Text;
                frmSearchItem.TopMost = false;
                frmSearchItem.Disposed += new EventHandler(FrmSearchItem_Disposed);
                frmSearchItem.Show(this);
            }

            frmSearchItem.Show(this);

        }

        public void ShowInvoiceDetailForm(int invoiceId)
        {
            if (frmInvoiceExp == null || frmInvoiceExp.IsDisposed)
            {
                frmInvoiceExp = new FrmInvoiceExplorer(this);
                frmInvoiceExp.Text = "Danh sách hóa đơn " + invoiceId;
                frmInvoiceExp.TabText = frmInvoiceExp.Text;
            }

            if (frmInvoiceDetail == null || frmInvoiceDetail.IsDisposed)
            {
                frmInvoiceDetail = new FrmInvoiceDetail(this);
                frmInvoiceDetail.Text = "Chi tiết hóa đơn";
                frmInvoiceDetail.TabText = frmInvoiceDetail.Text;
            }

            frmInvoiceDetail.InvoiceId = invoiceId;
            frmInvoiceDetail.Display(DigitalRune.Windows.Docking.DockState.Document);
        }

        public void ActiveInvoiceDetailForm()
        {
            if (frmInvoiceDetail != null && frmInvoiceDetail.IsDisposed)
            {
                frmInvoiceDetail.Activate();
            }
        }

        public  FrmInvoiceExplorer InvoiceExplorer
        {
             get { return this.frmInvoiceExp;}
        }

        public FrmBarcodePrinter BarcodePrinter
        {
            get { return this.frmBarcodePrinter; }
        }

        private void FrmSearchItem_Disposed(object sender, EventArgs e)
        {
            frmSearchItem = null;
        }

        private void mnPrintConfig_Click(object sender, EventArgs e)
        {
            if (printDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                SetBillPrinterNameFromRegistry(printDialog.PrinterSettings.PrinterName);
                IDockableForm[] forms = dockPanel.DocumentsToArray();
                foreach (IDockableForm f in forms)
                {
                    if (f is FrmSale)
                    {
                        FrmSale fs = (FrmSale)f;
                        fs.SetPrinterName(printDialog.PrinterSettings.PrinterName);
                    }
                }
            }
        }

        public static string GetBillPrinterNameFromRegistry() {
            object co = registryKey.GetValue("printer_bill");
            if (co != null)
            {
                return co.ToString();
            }
            else
            {
                registryKey.SetValue("printer_bill", RuntimeData.GetPrinterBillName());
            }

            return RuntimeData.GetPrinterBillName();
        }


        public static void SetBillPrinterNameFromRegistry(string printerName)
        {
            registryKey.SetValue("printer_bill", printerName);
        }

        private void mnInvoice_Click(object sender, EventArgs e)
        {
            ShowInvoiceExplorerForm();
        }

        private void mnImportItemBranch_Click(object sender, EventArgs e)
        {
            ShowImportItemBranchForm();
        }

        private void mnCheckStock_Click(object sender, EventArgs e)
        {
            ShowCheckStockForm();
        }

        private void mnReportMoneyIncome_Click(object sender, EventArgs e)
        {
            ShowReportIncome();
        }

        private void mnPrintBarcode_Click(object sender, EventArgs e)
        {
            if (frmBarcodePrinter != null)
            {
                frmBarcodePrinter.Close();
                frmBarcodePrinter = null;
            }

            ShowBarcodePrinter();
        }

        #region Report Daily
        private void doDailyReport()
        {
            while (isReportStop == false)
            {
                try
                {
                    DateTime now = DateTime.Now;
                    if (now.Hour == 18)
                    {
                        if (now.Minute >= 10 && now.Minute <= 45)
                        //if (now.Minute >= 00 && now.Minute <= 59)
                        {

                            if (!hasSendReport)
                            {
                                string sub = string.Format("[CALEMSHOP {0}] Daily Report {1}", RuntimeData.GetBranchId() ,now.ToString("dd-MM-yyyy HH:mm"));
                                StringBuilder builder = new StringBuilder();
                                builder.Append(@"<h3>Ngày :" + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss") + "</h1>");
                                builder.Append(@"<hr>");
                                builder.Append(System.Environment.NewLine);
                                builder.Append(@"+ Tổng tiền thu được : <b>");
                                builder.Append(Database.totalIncomeToday().ToString("#,0")).Append(" VNĐ </b>");
                                builder.Append(@"<br/>");
                                builder.Append(@"+ Số khách trả hàng :");
                                builder.Append(Database.countInvoiceReturnToday()).Append(" lần");
                                builder.Append(@"<br/>");
                                builder.Append(@"+ Tổng số hóa đơn bán :");
                                builder.Append(Database.countInvoice(DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")));
                                builder.Append(@"<br/>");

                                DataTable db = Database.reportSellers(DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));
                                if (db != null)
                                {
                                    foreach (DataRow r in db.Rows)
                                    {
                                        string dname = (string)r["seller"];
                                        double value = double.Parse(r["sellerIncome"].ToString());
                                        builder.Append(string.Format("<b>+ {0} </b> bán được : {1}</b>", dname, value.ToString("#,0")));
                                        builder.Append(@"<br/>");
                                    }

                                }

                                if (registryKey != null)
                                {
                                    string reportKeyValue = now.ToString("dd-MM-yyyy hh");
                                    string value = (string)registryKey.GetValue("report", string.Empty);
                                    if (string.IsNullOrEmpty(value) == false && string.Compare(value, reportKeyValue, true) == 0)
                                    {
                                        hasSendReport = true;
                                    }
                                }

                                if (hasSendReport == false)
                                {
                                    UpdateProgressBar(10, "Begin sending report ...");
                                    hasSendReport = GMail.sendMail(new string[] { "calemshop@gmail.com", "trucmai2211@yahoo.com", "vinhan21@yahoo.com.vn" }, sub, builder.ToString());
                                    if (hasSendReport)
                                    {
                                        string reportKeyValue = now.ToString("dd-MM-yyyy hh");
                                        if (registryKey != null)
                                        {
                                            registryKey.SetValue("report", reportKeyValue);
                                        }
                                    }

                                    UpdateProgressBar(100, "Send report success");
                                }

                                
                                if (hasSendReport)
                                {
                                    UpdateStatusMessage("Send report success");
                                }
                            }

                            //==================
                            if (!hasBackup)
                            {
                                UpdateProgressBar(10, "Begin backup data ...");
                                hasBackup = BackupUtil.doBackupData();
                                if (hasBackup)
                                {
                                    UpdateProgressBar(100, "Backup data success");
                                }
                            }
                            else
                            {
                                UpdateProgressBar(-1, "Done");
                            }
                        }
                        else
                        {
                            UpdateStatusMessage("Daily report is active");
                        }
                    }
                    else
                    {
                        hasSendReport = false;
                        hasBackup = false;
                        UpdateStatusMessage("Daily report is active");
                    }

                    Thread.Sleep(5000);
                }
                catch (ThreadInterruptedException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    UpdateStatusMessage(ex.Message);
                }
            }

        }
        #endregion

        private void FrmCalemShop_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                isReportStop = true;
                reportThread.Interrupt();
                reportThread.Join();
            }
            catch (Exception) { }
        }

        private void mnInputStock_Click(object sender, EventArgs e)
        {
            ShowInputStockForm();
        }

        private void FrmCalemShop_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Control && e.KeyCode == Keys.F)
                {
                    e.SuppressKeyPress = false;
                    ShowSearchItemForm();
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void mnCustomer_Click(object sender, EventArgs e)
        {
            ShowCustomerForm();
        }

        private void mnStaff_Click(object sender, EventArgs e)
        {
            ShowStaffForm();
        }
    }
}
